{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现使用Python编写get_best_k函数，实现选取最佳岭参数的功能，并基于iris数据集，求解建立Ridge回归的最佳岭参数k"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "def get_best_k(X,y,kmax=1,qnum=10,intercept=True):\n",
    "    \"\"\"\n",
    "    根据GCV方法，获得最佳岭参数k \n",
    "    X : 自变量的数据矩阵\n",
    "    y : 响应变量向量或矩阵\n",
    "    kmax : 岭参数的最大值\n",
    "    qnum : 将0~kmax的区间分成qnum等分\n",
    "    intercept : 是否计算戴距\n",
    "    \"\"\"\n",
    "    n = X.shape[0]\n",
    "    if intercept:\n",
    "        X = np.c_[X,[1]*n]\n",
    "    \n",
    "    gcv_list = []\n",
    "    kvalues = np.linspace(0,kmax,qnum+1)\n",
    "    for k in kvalues:\n",
    "        mk = np.matmul(np.matmul(X,np.linalg.inv(np.matmul(X.T,X)+k*np.identity(X.shape[1]))),X.T)\n",
    "        yk = np.matmul(mk,y)\n",
    "        trmk = np.trace(mk)\n",
    "        gcv = np.sum((y - yk)**2)/(n*(1-trmk/n)**2)\n",
    "        gcv_list.append(gcv)\n",
    "        \n",
    "    return kvalues[np.argmin(gcv_list)], np.min(gcv_list)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(0.59, 0.03773870908890475)"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "iris=pd.read_csv(\"http://image.cador.cn/data/iris.csv\")\n",
    "x = iris.iloc[:,[0,1,2]].values\n",
    "y = iris.iloc[:,3].values\n",
    "get_best_k(x, y, qnum = 100)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
